package com.everflourish.yeah100.act.markingsystem;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseFragment;
import com.everflourish.yeah100.entity.Examination;
import com.everflourish.yeah100.entity.clazz.ClassManage;
import com.everflourish.yeah100.entity.clazz.ClassManagerModel;
import com.everflourish.yeah100.entity.marking.ExaminationBase;
import com.everflourish.yeah100.entity.marking.Teacher;
import com.everflourish.yeah100.entity.marking.TeacherModel;
import com.everflourish.yeah100.http.MarkingSystemRequest;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.CommonUtil;
import com.everflourish.yeah100.utils.DateFormatUtil;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.KeyBoardUtils;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.StringUtil;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/6/3.
 * 时间：2016/6/3
 */
public class FragmentExamCreate extends BaseFragment implements View.OnClickListener, View.OnTouchListener, DatePickerDialog.OnDateSetListener {

    private EditText mExamNameEt, mExamSubjectEt, mExamTimeEt, mExamClassEt, mExamTeacherEt;
    private TextInputLayout mExamNameTil;
    private TextView mExamCreateSureBt, mRefreshTv;
    private LinearLayout mExaminationContentLl;
    private FrameLayout mFrameLayout;
    private ProgressWheel mProgress;
    private MarkingSystemRequest mRequest;
    private MarkingMenuActivity mMarkingMenuActivity;
    public ExaminationBase mExaminationBase, mBakupExaminationBase;
    private long lastModifiedTime;
    private String mExaminationId;
    private ArrayList<ClassManage> classManages;
    private ArrayList<ClassManagerModel> mClazzList;
    private ArrayList<Teacher> teacherList;
    private ArrayList<TeacherModel> mTeacherModelList;
    private ListPopupWindow mSubjectPopupWindow;
    private boolean isPrepared;  //  标志位，标志已经初始化完成。
    private Context mContext;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_create_exam, container, false);
        isPrepared = true;
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        initData();
        initView();
        configView();
        initViewData();
        isPrepared = false;
    }

    private void initData() {
        mContext = mMarkingMenuActivity = (MarkingMenuActivity) getActivity();
        mRequest = MarkingSystemRequest.getInstance();
        classManages = new ArrayList<ClassManage>();
        mClazzList = new ArrayList<ClassManagerModel>();
        teacherList = new ArrayList<Teacher>();
        mExaminationBase = new ExaminationBase();
    }

    private void initView() {
        mFrameLayout = (FrameLayout) getView().findViewById(R.id.exam_create_fl);
        mExaminationContentLl = (LinearLayout) getView().findViewById(R.id.exam_content_ll);
        mRefreshTv = (TextView) getView().findViewById(R.id.include_refresh_tv);
        mRefreshTv.setTextColor(mContext.getResources().getColor(R.color.marking_appbar_primaryDark));
        mRefreshTv.setOnClickListener(this);
        mProgress = (ProgressWheel) getView().findViewById(R.id.exam_progress);
        mExamNameEt = (EditText) getView().findViewById(R.id.exam_name_et);
        mExamSubjectEt = (EditText) getView().findViewById(R.id.exam_subject_et);
        mExamTimeEt = (EditText) getView().findViewById(R.id.exam_time_et);
        mExamClassEt = (EditText) getView().findViewById(R.id.exam_classes_et);
        mExamTeacherEt = (EditText) getView().findViewById(R.id.exam_teacher_et);
        mExamNameTil = (TextInputLayout) getView().findViewById(R.id.exam_name_til);
        mExamCreateSureBt = (TextView) getView().findViewById(R.id.exam_create_sure);
        mExamTimeEt.setOnClickListener(this);
        mExamTeacherEt.setOnClickListener(this);
        mExamClassEt.setOnClickListener(this);
        mExamCreateSureBt.setOnClickListener(this);
        mExamSubjectEt.setOnClickListener(this);
        mExamClassEt.setOnClickListener(this);
        mFrameLayout.setOnTouchListener(this);
        showDialogItems();
    }

    private void initViewData() {  //  修改
        if (mMarkingMenuActivity.mExamination != null) {
            getBiascInfoRequest(mMarkingMenuActivity.mExamination.getId(), false);
        } else {  // 新建考试
            createExaminationInfoRequest();
        }
    }

    private void configView() {
//        mExaminationContentLl.setVisibility(View.GONE);
//        mProgress.setVisibility(View.VISIBLE);
    }

    /**
     * 获取基础信息请求
     *
     * @param examinationId
     */
    private void getBiascInfoRequest(String examinationId, final boolean isUpload) {
        if (!isUpload) {
            mLoadDialog = LoadDialog.show(mContext, null, "加载中...", mQueue);
        }
        JsonObjectRequest request = mRequest.getBasicInfoRequest(examinationId,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        getBasicInfoExaminationListener(response, isUpload);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
//                        mProgress.setVisibility(View.GONE);
                        LoadDialog.dismiss(mLoadDialog);
                        mExaminationContentLl.setVisibility(View.GONE);
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取考试信息失败");
                    }
                });
        mQueue.add(request);
//        mQueue.start();
    }

    /**
     * 创建考试请求
     */
    private void createExaminationInfoRequest() {
        mLoadDialog = LoadDialog.show(mContext, null, "加载中...", mQueue);
        JsonObjectRequest request = mRequest.createBasicInfoRequest(new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                createExaminationListener(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                mProgress.setVisibility(View.GONE);
                LoadDialog.dismiss(mLoadDialog);
                mExaminationContentLl.setVisibility(View.GONE);
                mRequest.disposeError(mContext, mLoadDialog, error, "创建考试失败");
            }
        });
        mQueue.add(request);
//        mQueue.start();
    }

    /**
     * 修改基础信息请求
     *
     * @param examinationBase
     */
    private void updateBasicInfoRequest(ExaminationBase examinationBase) {
        mLoadDialog = LoadDialog.show(mContext, null, "加载中...", mQueue);
//        mProgress.setVisibility(View.VISIBLE);
        JsonObjectRequest request = mRequest.updateBasicInfoRequest(
                examinationBase, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        updateBasicInfoExaminationListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "上传考试信息失败");
//                        mProgress.setVisibility(View.GONE);
                    }
                });
        mQueue.add(request);
//        mQueue.start();
    }

    /**
     * 获取考试信息建监听
     *
     * @param response
     */
    private void getBasicInfoExaminationListener(JSONObject response, boolean isUpload) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONObject eJsonObject = response.getJSONObject("examination");
                Gson gson = new Gson();
                mExaminationBase = gson.fromJson(eJsonObject.toString(),
                        ExaminationBase.class);
                mBakupExaminationBase = null;
                mBakupExaminationBase = (ExaminationBase) mExaminationBase.deepCopy();
                if (mExaminationBase == null) {
                    MyToast.showShort(mContext, "获取考试信息失败");
                    return;
                }
                if (isUpload) {
                    MyToast.showShort(mContext, "修改成功");
                }
                if (mMarkingMenuActivity.mFragmentStandardAnswer != null) {
                    mMarkingMenuActivity.mFragmentStandardAnswer.refreshData();
                }
                if (mMarkingMenuActivity.mFragmentStandardAnswer != null) {
                    mMarkingMenuActivity.mFragmentReadPaper.refreshData();
                }
//                if (mMarkingMenuActivity.mExamination != null) {
//                    mMarkingMenuActivity.mExamination
//                            .setLastModifiedTime(mExaminationBase
//                                    .getLastModifiedTime());
//                }
                // 获取考试信息成功，设置控件显示
                setViewData();
                setViewVisible();
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07021_000001E);
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07022_000012E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07023_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.readcard_070299_999999E);
            } else {
                MyToast.showShort(mContext, "获取考试信息失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "获取考试信息失败");
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
//            mProgress.setVisibility(View.GONE);
            LoadDialog.dismiss(mLoadDialog);
            mExaminationContentLl.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 创建考试监听
     *
     * @param response
     */
    private void createExaminationListener(JSONObject response) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                mExaminationId = response.getString("examinationId");
                lastModifiedTime = response.getLong("lastModifiedTime");
                if (mMarkingMenuActivity.mExamination == null) {
                    mMarkingMenuActivity.mExamination = new Examination();
                }
                mMarkingMenuActivity.mExamination.setId(mExaminationId);
                mMarkingMenuActivity.mExamination.setStatisticTiggered("N");
                mMarkingMenuActivity.isUpdateExamination = true;
                getBiascInfoRequest(mExaminationId, true);
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showLong(mContext, R.string.readcard_07151_000001E);
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showLong(mContext, R.string.readcard_07152_000012E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showLong(mContext, R.string.readcard_071599_999999E);
            } else {
                MyToast.showLong(mContext, "创建考试失败");
            }
        } catch (Exception e) {
            MyToast.showLong(mContext, "创建考试失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
//            mProgress.setVisibility(View.GONE);
        }
    }

    /**
     * 修改基础信息监听
     *
     * @param response
     */
    private void updateBasicInfoExaminationListener(JSONObject response) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                lastModifiedTime = response.getLong("lastModifiedTime");
                mMarkingMenuActivity.isUpdateExamination = true;
//                mMarkingMenuActivity.mExamination
//                        .setLastModifiedTime(lastModifiedTime);
                //   重新获取考试基础信息
                getBiascInfoRequest(mMarkingMenuActivity.mExamination.getId(), true);
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07011_000001E);
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07012_000012E);
            } else if (resultCode.equals(ResultCode.result_200001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07013_200001E);
            } else if (resultCode.equals(ResultCode.result_200004E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07014_200004E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07015_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_version_unlike_exception_777777E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07018_777777E);
            } else if (resultCode.equals(ResultCode.result_300021E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07017_300021E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.readcard_070199_999999E);
            } else {
                MyToast.showShort(mContext, "修改考试失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "修改考试失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
//            mProgress.setVisibility(View.GONE);
        }
    }

    /**
     * 设置控件数据
     */
    private void setViewData() throws ParseException {
        // 设置考试名称
        mExamNameEt.setText(mExaminationBase.getName());
        // 设置科目名称
        mExamSubjectEt.setText(mExaminationBase.getSubject());
        // 设置考试时间
        mExamTimeEt.setText(DateFormatUtil.convertStrToStr(mExaminationBase.getDate(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd E"));
        // 设置班级列表
        if (mExaminationBase.getClasses() != null) {
            classManages.clear();
            classManages.addAll(mExaminationBase.getClasses());
            initClasses();
        }
        setClassList(classManages);
        mExamClassEt.setText(setClassNameList(mExaminationBase.getClasses()));
        // 设置共享老师列表
        if (mExaminationBase.getTeacherUsers() != null) {
            teacherList.clear();
            teacherList.addAll(mExaminationBase.getTeacherUsers());
        }
        setTeacherList(teacherList);
        mExamTeacherEt.setText(setTeacherNameList(mExaminationBase.getTeacherUsers()));
        lastModifiedTime = mExaminationBase.getLastModifiedTime();
    }

    /**
     * 设置班级列表(班级列表页面的数据 mClazzList)
     *
     * @param clazzes
     */
    private void setClassList(List<ClassManage> clazzes) {
//        mClazzList = new ArrayList<ClassManagerModel>();
        mClazzList.clear();
        for (ClassManage c : clazzes) {
            ClassManagerModel model = new ClassManagerModel();
            model.setClassManage(c);
            model.setIsCheck(true);
            mClazzList.add(model);
        }
    }

    /**
     * 设置班级名称列表
     *
     * @param clazzes
     */
    private String setClassNameList(List<ClassManage> clazzes) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < clazzes.size(); i++) {
            stringBuffer.append(clazzes.get(i).getName().toString());
            if (i != clazzes.size() - 1) {
                stringBuffer.append("，");
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 初始化班级列表中，上传不需要的字段
     */
    private void initClasses() {
        for (int i = 0; i < classManages.size(); i++) {
            ClassManage classManage = classManages.get(i);
            classManage.setClassNo(null);
            // classManage.setCreateTime(null);
            classManage.setImagePath(null);
            classManage.setSharingNo(null);
            // classManage.setSize(null);
        }
    }

    /**
     * 设置共享老师列表 （页面数据 ）
     *
     * @param teacherList
     */
    private void setTeacherList(List<Teacher> teacherList) {
        mTeacherModelList = new ArrayList<TeacherModel>();
        mTeacherModelList.clear();
        for (Teacher t : teacherList) {
            TeacherModel teacherModel = new TeacherModel();
            teacherModel.setTeacher(t);
            teacherModel.setIsDelete(false);
            teacherModel.setIsCheck(true);
            mTeacherModelList.add(teacherModel);
        }
    }

    /**
     * 设置共享老师名称列表
     *
     * @param teacherList
     * @return
     */
    private String setTeacherNameList(List<Teacher> teacherList) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < teacherList.size(); i++) {
            stringBuffer.append(teacherList.get(i).getUserName());
            if (i != teacherList.size() - 1) {
                stringBuffer.append("，");
            }
        }
        return stringBuffer.toString();
    }

    private void setViewVisible() {
//        mExaminationContentLl.setVisibility(View.VISIBLE);
        mProgress.setVisibility(View.GONE);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }

    @Override
    public void onClick(View v) {
        KeyBoardUtils.closeKeybord(mExamNameEt, mContext);
        mFrameLayout.setFocusable(true);
        mFrameLayout.setFocusableInTouchMode(true);
        mFrameLayout.requestFocus();
        switch (v.getId()) {
            case R.id.exam_create_sure:   //  确认修改考试
                if (!StringUtil.isExamName(mExamNameEt.getText().toString().trim())) {
                    mExamNameTil.setError("考试名称在2~16字之间");
                    return;
                } else {
                    mExamNameTil.setErrorEnabled(false);
                    mExamNameTil.setError(null);
                }
                setExaminationBase();
                updateBasicInfoRequest(mExaminationBase);
                break;
            case R.id.exam_classes_et:   //  参考班级
                Intent classIntent = new Intent(mMarkingMenuActivity,
                        ClassExamActivity.class);
//                setClassList(classManages);
                classIntent.putExtra(IntentUtil.CLASS_LIST, mClazzList);
                startActivityForResult(classIntent, IntentUtil.E_CREATE_FLAG);
                break;
            case R.id.exam_subject_et:  //  科目选择
                mSubjectPopupWindow.setAnchorView(v);
                mSubjectPopupWindow.show();
                break;
            case R.id.exam_time_et:  //  考试时间选择
                Calendar now = Calendar.getInstance();
                DatePickerDialog dpd = DatePickerDialog.newInstance(this,
                        now.get(Calendar.YEAR),
                        now.get(Calendar.MONTH),
                        now.get(Calendar.DAY_OF_MONTH)
                );
//                dpd.setAccentColor(Color.parseColor("#9C27B0"));
                dpd.show(mMarkingMenuActivity.getFragmentManager(), "Datepickerdialog");
                break;
            case R.id.exam_teacher_et:  //  共享老师选择
                if (mMarkingMenuActivity.mExamination == null) {
                    return;
                }
                Intent intent = new Intent(mContext, TeacherShareActivity.class);
                intent.putExtra(IntentUtil.TEACHER_LIST, mTeacherModelList);
                intent.putExtra("isSelfCreate",
                        mMarkingMenuActivity.mExamination.isSelfCreate());
                startActivityForResult(intent, IntentUtil.E_CREATE_FLAG3);
                break;
            case R.id.include_refresh_tv:  // 再试一试
                mProgress.setVisibility(View.VISIBLE);
                if (mMarkingMenuActivity.mExamination == null) {
                    createExaminationInfoRequest();
                } else {
                    getBiascInfoRequest(mMarkingMenuActivity.mExamination.getId(), false);
                }
                break;
            default:
                break;
        }
    }

    private void setExaminationBase() {
        KeyBoardUtils.closeKeybord(mExamNameEt, mContext);
        mExaminationBase.setName(mExamNameEt.getText().toString().trim());
        mExaminationBase.setSubject(mExamSubjectEt.getText().toString());
        mExaminationBase.setDate(mExamTimeEt.getText().toString());
        String tempStr = "";
        try {
            long dateTemp = DateFormatUtil.convertStrToMilliseconds(mExamTimeEt.getText().toString(), "yyyy-mm-dd E");
            tempStr = DateFormatUtil.convertMillisecondsToStr(
                    dateTemp, "yyyy-mm-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        mExaminationBase.setDate(tempStr);
        initClasses();
        ArrayList<ClassManage> mUploadClassManages = CommonUtil.deepCopy(classManages);
        for (ClassManage c : mUploadClassManages) {
            if (c.getRosterClassId() == null) {
                c.setRosterClassId(c.getId());
                c.setId(null);
            }
            c.setCreateTime(null);
            c.setStudents(null);
            c.setName(null);
            c.setSize(null);
        }
        mExaminationBase.setClasses(mUploadClassManages);
        ArrayList<Teacher> mUploadTeacherList = CommonUtil.deepCopy(teacherList);
        ArrayList<String> userIds = new ArrayList<String>();
        if (mUploadTeacherList != null) {
            for (Teacher t : mUploadTeacherList) {
                userIds.add(t.getUserId());
            }
        }
        mExaminationBase.setUserIds(userIds);
        mExaminationBase.setTeacherUsers(null);
        mExaminationBase.setLastModifiedTime(lastModifiedTime);
    }


    /**
     * 判断是否有修改过基础信息
     *
     * @return
     */
    public boolean setIsChange() {
        if (mContext == null) {
            return false;
        }
        setExaminationBase();
        boolean isChange = false;
        if (mExaminationBase == null || mBakupExaminationBase == null) {
            return false;
        }
        if (!mExaminationBase.getName().trim().equals(mBakupExaminationBase.getName())) {
            return true;
        }
        if (!mExaminationBase.getSubject().trim().equals(mBakupExaminationBase.getSubject())) {
            return true;
        }
        if (!mExaminationBase.getDate().equals(mBakupExaminationBase.getDate())) {
            try {
                long mExaminationBaseDate = DateFormatUtil.convertStrToMilliseconds(mBakupExaminationBase.getDate(), "yyyy-mm-dd");
                long mBakExaminationBaseDate = DateFormatUtil.convertStrToMilliseconds(mExaminationBase.getDate(), "yyyy-mm-dd");
                if (mExaminationBaseDate == mBakExaminationBaseDate) {
                    return false;
                }
                return true;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        List<ClassManage> updateClazzs = mExaminationBase.getClasses();
        List<ClassManage> oldClazzs = mBakupExaminationBase.getClasses();
        if (updateClazzs != null && oldClazzs != null) {
            if (updateClazzs.size() != oldClazzs.size()) {
                return true;
            }
            for (ClassManage u : updateClazzs) {
                for (int i = 0; i < oldClazzs.size(); i++) {
                    ClassManage o = oldClazzs.get(i);
                    if (u.getId().equals(o.getId())) {
                        break;
                    } else {
                        if (i == oldClazzs.size() - 1) {
                            return true;
                        }
                    }
                }
            }
        }
        List<Teacher> updateTeachers = mExaminationBase.getTeacherUsers();
        List<Teacher> oldTeachers = mBakupExaminationBase.getTeacherUsers();
        if (updateTeachers != null && oldTeachers != null) {
            if (updateTeachers.size() != oldTeachers.size()) {
                return true;
            }
            for (Teacher u : updateTeachers) {
                for (int i = 0; i < oldTeachers.size(); i++) {
                    Teacher o = oldTeachers.get(i);
                    if (u.getUserId().equals(o.getUserId())) {
                        break;
                    } else {
                        if (i == oldTeachers.size() - 1) {
                            return true;
                        }
                    }
                }
            }
        }
        return isChange;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IntentUtil.E_CREATE_FLAG) {
            if (resultCode == MarkingMenuActivity.RESULT_OK) {
                mClazzList = (ArrayList<ClassManagerModel>) data
                        .getSerializableExtra(IntentUtil.CLASS_LIST);
                if (mClazzList != null) {
                    setEClass(mClazzList);
                }
            }
        } else if (requestCode == IntentUtil.E_CREATE_FLAG3) {
            if (resultCode == MarkingMenuActivity.RESULT_OK) {
                ArrayList<TeacherModel> mTempTeacherModelList = (ArrayList<TeacherModel>) data
                        .getSerializableExtra(IntentUtil.TEACHER_LIST);
                if (mTempTeacherModelList != null) {
                    setETeacher(mTempTeacherModelList);
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 设置选中的班级
     *
     * @param list
     */
    private void setEClass(List<ClassManagerModel> list) {
        classManages.clear();
        for (ClassManagerModel model : list) {
            boolean isChecked = model.isCheck();
            if (isChecked) {
                ClassManage clazz = model.getClassManage();
                classManages.add(clazz);
            }
        }
        mExamClassEt.setText(setClassNameList(classManages));
    }

    private void setETeacher(List<TeacherModel> list) {
        teacherList.clear();
        for (TeacherModel teacherModel : list) {
            boolean isChecked = teacherModel.isCheck();
            if (isChecked) {
                Teacher t = teacherModel.getTeacher();
                teacherList.add(t);
            }
        }
        setTeacherList(teacherList);
        mExamTeacherEt.setText(setTeacherNameList(teacherList));
    }

    /**
     * 选择科目lsit弹出框
     */
    private void showDialogItems() {
        String[] subjects = mContext.getResources().getStringArray(
                R.array.subjects);
        final List<String> items = new ArrayList<String>();
        for (String s : subjects) {
            items.add(s);
        }
        mSubjectPopupWindow = new ListPopupWindow(mMarkingMenuActivity);
        mSubjectPopupWindow.setAdapter(new ArrayAdapter<String>(mMarkingMenuActivity, R.layout.item_subject_popup, items));
        mSubjectPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mSubjectPopupWindow.setHeight(600);
//        mSubjectPopupWindow.setAnchorView(mExamSubjectEt);//设置ListPopupWindow的锚点，即关联PopupWindow的显示位置和这个锚点
        mSubjectPopupWindow.setModal(true);// 设置是否是模式
        mSubjectPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mExamSubjectEt.setText(items.get(position));
                mSubjectPopupWindow.dismiss();
            }
        });
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        try {
            mExamTimeEt.setText(DateFormatUtil.convertMillisecondsToStr(
                    DateFormatUtil.getTime(year, monthOfYear, dayOfMonth), "yyyy-MM-dd E"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mFrameLayout.setFocusable(true);
        mFrameLayout.setFocusableInTouchMode(true);
        mFrameLayout.requestFocus();
        return super.getActivity().onTouchEvent(event);
    }
}